package com.wj.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author wj
 * @since 2022-05-26
 */
@Getter
@Setter
@TableName("t_user")
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    //用户信息id
    @TableField("user_info_id")
    private Integer userInfoId;

    //用户名
    @TableField("username")
    private String username;

    //密码
    @TableField("password")
    private String password;

    //登录类型
    @TableField("login_type")
    private Integer loginType;

    //ip地址
    @TableField("ip_addr")
    private String ipAddr;

    //id源头
    @TableField("ip_source")
    private String ipSource;

    //是否禁用
    @TableField("is_enable")
    private Boolean isEnable;

    //创建时间
    @TableField("create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "Asia/Shanghai")
    private LocalDateTime createTime;

    //最后登录时间
    @TableField("last_login_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "Asia/Shanghai")
    private LocalDateTime lastLoginTime;

    //用户角色
    @TableField(exist = false)
    private List<Role> roles;

    //用户角色
    @TableField(exist = false)
    private List<SimpleGrantedAuthority> rolesEn;


    @JsonIgnore//因为是不确定的值，防止json转换出问题
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (rolesEn != null){
            return rolesEn;
        }
        List<SimpleGrantedAuthority> collect = roles.stream().map(role -> new SimpleGrantedAuthority(role.getRoleName())).collect(Collectors.toList());
        return collect;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return isEnable;
    }
}
